import { useState, useEffect, useRef } from 'react'
import { Card, Button, Table, Tag, Switch, message, Popconfirm, Drawer, Form, Input, InputNumber } from 'antd'
import { getSkuList, changStatus, addSku, editSku, delSkus } from '@/api/skus'
import type { InputRef } from 'antd'
function Skus() {
  const [levelList, setLevelList] = useState([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  useEffect(() => {
    getList()
  }, [page])
  const getList = () => {
    getSkuList(page).then(res => {
      if (res.status === 200) {
        console.log(res.data)
        setLevelList(res.data.list)
        setTotal(res.data.totalCount)
      }
    })
  }
  const switchChange = (status: boolean, id: number) => {
    changStatus(id, { status: !status }).then(res => {
      if (res.status === 200) {
        getList()
        message.success('修改成功')
      } else {
        message.error('修改失败')
      }
    })
  }
  const delLevel = (id: number) => {
    delSkus([id]).then(res => {
      if (res.status === 200) {
        getList()
        message.success('删除成功')
      } else {
        message.error('删除失败')
      }
    })
  }
  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '规格值',
      dataIndex: 'default',
      key: 'default'
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order'
    },
    {
      title: '状态',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Switch
            checked={data.status}
            onChange={() => {
              switchChange(data.status, data.id)
            }}
          ></Switch>
        </div>
      )
    },
    {
      title: '操作',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          <Tag
            color='lime'
            onClick={() => {
              editBtn(data)
            }}
          >
            修改
          </Tag>
          <Popconfirm
            title='注意'
            description='你确认要删除该等级吗？'
            onConfirm={() => {
              delLevel(data.id)
            }}
            okText='确认'
            cancelText='取消'
          >
            <Tag color='red'>删除</Tag>
          </Popconfirm>
        </div>
      )
    }
  ]
  // 添加修改弹框
  const [openDrawer, setOpenDrawer] = useState(false)
  const [editId, setEditId] = useState(0)
  const [form] = Form.useForm()
  const [sku, setSku] = useState<any[]>([])
  const [inputVisible, setInputVisible] = useState(false)
  const inputRef = useRef<InputRef>(null)
  const addBtn = () => {
    setEditId(0)
    setOpenDrawer(true)
    form.resetFields()
    setSku([])
  }
  useEffect(() => {
    if (inputRef && inputVisible) {
      inputRef.current?.focus()
    }
  }, [inputVisible])
  const handleKeyDown = (e: any) => {
    if (e.key === 'Enter') {
      // 防止默认行为，比如在表单中触发提交
      e.preventDefault()
      setSkuData(e)
    }
  }
  const setSkuData = (event: React.FocusEvent<HTMLInputElement>) => {
    const inputValue = event.target.value
    if (inputValue) {
      if (!sku.includes(inputValue)) {
        setSku(prevSku => [...prevSku, inputValue])
      }
    }
    setInputVisible(false)
  }
  const addSkuText = () => {
    setInputVisible(true)
  }
  const editBtn = (data: any) => {
    setOpenDrawer(true)
    setEditId(data.id)
    form.setFieldsValue({
      order: data.order,
      name: data.name,
      status: data.status
    })
    setSku(data.default.split(','))
  }
  const saveAddLevelBtn = () => {
    form.validateFields().then(values => {
      if (editId !== 0) {
        editSku(editId, { ...values }).then(res => {
          if (res.status === 200) {
            message.success('修改成功')
            getList()
            setOpenDrawer(false)
          }
        })
        return
      }

      addSku({ ...values }).then(res => {
        if (res.status === 200) {
          message.success('添加成功')
          getList()
          setOpenDrawer(false)
        }
      })
    })
  }
  const handleClose = (tag: string) => {
    let data = sku.filter(o => o !== tag)
    setSku(data)
  }
  const [checkIds, setCheckIds] = useState<number[]>([])
  const rowSelection: any = {
    type: 'checkbox',
    onChange: (selectedRowKeys: React.Key[]) => {
      let data = selectedRowKeys as number[]
      setCheckIds(data)
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  }
  const batchDelete = () => {
    if (checkIds.length === 0) {
      message.error('请选择要删除的规格')
    } else {
      delSkus(checkIds).then(res => {
        if (res.status === 200) {
          getList()
          message.success('删除成功')
          setCheckIds([])
        } else {
          message.error('删除失败')
        }
      })
    }
  }
  const TagChild = (
    <div>
      {sku.map((tag: any) => (
        <span key={tag} style={{ display: 'inline-block' }}>
          <Tag
            color='processing'
            closable
            onClose={e => {
              e.preventDefault()
              handleClose(tag)
            }}
          >
            {tag}
          </Tag>
        </span>
      ))}
    </div>
  )

  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={saveAddLevelBtn}>
        提交
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setOpenDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  useEffect(() => {
    form.setFieldsValue({ default: sku.join(', ') })
  }, [sku, form])
  return (
    <>
      <Card>
        <Button onClick={addBtn} className='mr-10'>
          新增
        </Button>
        <Button type='primary' danger onClick={batchDelete} disabled={checkIds.length === 0}>
          批量删除
        </Button>
        <Table
          columns={columns}
          dataSource={levelList}
          rowKey='id'
          pagination={{ total }}
          onChange={(e: any) => {
            setPage(e.current)
          }}
          rowSelection={rowSelection}
        />
      </Card>
      <Drawer
        title={editId === 0 ? '新增规格' : '修改规格'}
        onClose={() => {
          setOpenDrawer(false)
        }}
        open={openDrawer}
        footer={btn}
      >
        <Form form={form}>
          <Form.Item name='name' label='规格名称' rules={[{ required: true, message: '请输入规格名称' }]}>
            <Input placeholder='请输入规格名称' />
          </Form.Item>
          <Form.Item name='order' label='排序' rules={[{ required: true, message: '请输入排序' }]} initialValue={50}>
            <InputNumber min={1} max={1000} keyboard />
          </Form.Item>
          <Form.Item name='status' label='状态' rules={[{ required: true }]} initialValue={true}>
            <Switch></Switch>
          </Form.Item>

          <Form.Item name='default' label='规格值' rules={[{ required: true, message: '规格值不能为空' }]} initialValue={true}>
            {TagChild}
            {inputVisible ? (
              <>
                <div>
                  <Input ref={inputRef} style={{ width: '80px' }} onBlur={setSkuData} onKeyDown={handleKeyDown} />
                </div>
              </>
            ) : (
              <>
                <Button size='small' onClick={addSkuText}>
                  +添加值
                </Button>
              </>
            )}
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}
export default Skus
